package cn.wikiflyer.beikang.utils;

import java.util.ArrayList;
import java.util.List;

import kankan.wheel.widget.OnWheelChangedListener;
import kankan.wheel.widget.WheelView;
import kankan.wheel.widget.adapters.ArrayWheelAdapter;
import cn.wikiflyer.beikang.act.user.adapter.AddressWheelAdapter;
import cn.wikiflyer.jft.db.DBManager;
import cn.wk.libs4a.utils.L;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

/**
 * 地址管理：省市区的管理
 */
public class AddressUtil {

	private Context context;

	private DBManager dbManager;
	private SQLiteDatabase database;
	private List<RegionBean> provinceBeans;
	private List<RegionBean> cityBeans;
	private List<RegionBean> areaBeans;

	private WheelView proWheel;
	private WheelView cityWheel;
	private WheelView areaWheel;

	private int defProId, defCityId, defAreaId = 0; // 设置默认值id

	public AddressUtil(Context context) {
		super();
		this.context = context;
		init();
	}

	/**
	 * 初始化数据
	 */
	private void init() {
		cityBeans = new ArrayList<RegionBean>();
		areaBeans = new ArrayList<RegionBean>();

		dbManager = new DBManager(context);
		dbManager.openDataBase();
		dbManager.closeDatabase();
		database = SQLiteDatabase.openOrCreateDatabase(DBManager.DB_PATH + "/"
				+ DBManager.DB_NAME, null);
		provinceBeans = getProvinceNames();
		database.close();
	}

	public void initWheel(WheelView proWheel, WheelView cityWheel,
			WheelView areaWheel) {
		this.proWheel = proWheel;
		this.cityWheel = cityWheel;
		this.areaWheel = areaWheel;
	}

	/**
	 * 初始化 WheelView默认数据
	 */
	public void setInitData() {
		proWheel.setViewAdapter(new AddressWheelAdapter(context, provinceBeans));
		// 添加change事件
		proWheel.addChangingListener(new WheelChangedListener());
		// 添加change事件
		cityWheel.addChangingListener(new WheelChangedListener());
		// 添加change事件
		areaWheel.addChangingListener(new WheelChangedListener());
		proWheel.setVisibleItems(5);
		cityWheel.setVisibleItems(5);
		areaWheel.setVisibleItems(5);
		updateCities(0);
	}

	/**
	 * 设置显示数据,传入id
	 */
	public void setUserData(int proId, int cityId, int areaId) {
		defProId = proId;
		defCityId = cityId;
		defAreaId = areaId;
		for (int i = 0; i < provinceBeans.size(); i++) {
			if (provinceBeans.get(i).regionId.equals("" + defProId)) {
				proWheel.setCurrentItem(i);
			}
		}

		// proWheel.setCurrentItem(proPostion);
		// cityWheel.setCurrentItem(cityPostion);
		// areaWheel.setCurrentItem(areaPosition);
	}

	/**
	 * 获取省份列表数据
	 */
	private ArrayList<RegionBean> getProvinceNames() {
		ArrayList<RegionBean> names = new ArrayList<RegionBean>();
		Cursor cursor = database
				.rawQuery(
						"select * from v9_linkage_20150429 where parentid=0 and keyid=1 ",
						null);
		for (int i = 0; i < cursor.getCount(); i++) {
			cursor.moveToPosition(i);
			RegionBean province = new RegionBean();
			province.regionId = cursor.getString(cursor
					.getColumnIndex("linkageid"));// region_id
			province.regionName = cursor.getString(cursor
					.getColumnIndex("name"));// region_name
			province.parentId = cursor.getString(cursor
					.getColumnIndex("parentid"));
			// province.regionCode = cursor.getString(cursor
			// .getColumnIndex("region_code"));
			province.regionCode = "1";
			names.add(province);
		}
		return names;
	}

	/**
	 * 更新省份对应Index的城市列表
	 */
	private void updateCities(int indexProvince) {
		RegionBean mProvinceBean = provinceBeans.get(indexProvince);
		String provinceId = mProvinceBean.regionId;
		database = SQLiteDatabase.openOrCreateDatabase(DBManager.DB_PATH + "/"
				+ DBManager.DB_NAME, null);
		cityBeans.clear();
		Cursor cursor = database.rawQuery(
				"select * from v9_linkage_20150429 where parentid="
						+ provinceId, null);
		L.wj("cursor.count :" + cursor.getCount());
		for (int i = 0; i < cursor.getCount(); i++) {
			cursor.moveToPosition(i);
			RegionBean city = new RegionBean();
			city.regionId = cursor
					.getString(cursor.getColumnIndex("linkageid"));// region_id
			city.regionName = cursor.getString(cursor.getColumnIndex("name"));// region_name
			city.parentId = cursor.getString(cursor.getColumnIndex("parentid"));
			// city.regionCode = cursor.getString(cursor
			// .getColumnIndex("region_code"));
			city.regionCode = "2";
			cityBeans.add(city);
		}
		database.close();
		cityWheel.setViewAdapter(new AddressWheelAdapter(context, cityBeans));
		if (defCityId != 0) {
			boolean needSelectLastOne = true;
			for (int i = 0; i < cityBeans.size(); i++) {
				if (cityBeans.get(i).regionId.equals("" + defCityId)) {
					cityWheel.setCurrentItem(i);
					needSelectLastOne = false;
					break;
				}
			}
			if (needSelectLastOne) {
				cityWheel.setCurrentItem(cityBeans.size() - 1);
			}

		}
		updateAreas(cityWheel.getCurrentItem());
	}

	/**
	 * 更新城市列表对应的区域列表
	 */
	private void updateAreas(int indexCity) {
		database = SQLiteDatabase.openOrCreateDatabase(DBManager.DB_PATH + "/"
				+ DBManager.DB_NAME, null);
		areaBeans.clear();
		System.out.println("lazy cityBeans l=" + cityBeans.size() + " index="
				+ indexCity);
		if (indexCity >= cityBeans.size()) {
			indexCity = cityBeans.size() - 1;
		}
		Cursor cursor = database.rawQuery(
				"select * from v9_linkage_20150429 where parentid="
						+ cityBeans.get(indexCity).regionId, null);
		for (int i = 0; i < cursor.getCount(); i++) {
			cursor.moveToPosition(i);
			RegionBean area = new RegionBean();
			area.regionId = cursor
					.getString(cursor.getColumnIndex("linkageid"));
			area.regionName = cursor.getString(cursor.getColumnIndex("name"));
			area.parentId = cursor.getString(cursor.getColumnIndex("parentid"));
			// area.regionCode = cursor.getString(cursor
			// .getColumnIndex("region_code"));
			area.regionCode = "3";
			areaBeans.add(area);
		}
		database.close();
		areaWheel.setViewAdapter(new AddressWheelAdapter(context, areaBeans));
		if (defAreaId != 0) {
			for (int i = 0; i < areaBeans.size(); i++) {
				if (areaBeans.get(i).regionId.equals("" + defAreaId)) {
					areaWheel.setCurrentItem(i);
					return;
				}
			}
			areaWheel.setCurrentItem(areaBeans.size()-1);
		}
	}

	public RegionBean getProvince() {
		return provinceBeans.get(proWheel.getCurrentItem());
	}

	public RegionBean getCity() {
		return cityBeans.get(cityWheel.getCurrentItem());
	}

	public RegionBean getArea() {
		try {
			return areaBeans.get(areaWheel.getCurrentItem());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 滚动监听
	 */
	class WheelChangedListener implements OnWheelChangedListener {
		@Override
		public void onChanged(WheelView wheel, int oldValue, int newValue) {
			if (wheel == proWheel) {
				updateCities(newValue);
				defProId = newValue;
			} else if (wheel == cityWheel) {
				updateAreas(newValue);
				defCityId = newValue;
			} else if (wheel == areaWheel) {
				defAreaId = newValue;
			}
		}
	}

	/**
	 * 拼接地址
	 */
	public String matchAddress(int province, int city, int area) {
		List<RegionBean> matchRegions = new ArrayList<RegionBean>();
		database = SQLiteDatabase.openOrCreateDatabase(DBManager.DB_PATH + "/"
				+ DBManager.DB_NAME, null);
		areaBeans.clear();
		Cursor cursor = database.rawQuery(
				"select * from v9_linkage_20150429 where linkageid in ("
						+ province + "," + city + "," + area + ")", null);
		for (int i = 0; i < cursor.getCount(); i++) {
			cursor.moveToPosition(i);
			RegionBean matchedRegion = new RegionBean();
			matchedRegion.regionId = cursor.getString(cursor
					.getColumnIndex("linkageid"));
			matchedRegion.regionName = cursor.getString(cursor
					.getColumnIndex("name"));
			matchRegions.add(matchedRegion);
		}
		database.close();
		StringBuilder sb = new StringBuilder();
		for (RegionBean regionBean : matchRegions) {
			sb.append(regionBean.regionName);
		}
		return sb.toString();
	}

}
